package com.lichao.utils;

import java.util.LinkedHashMap;
import java.util.Map;

public class PollingMapExample {

    private Map<String, String> map = new LinkedHashMap<>();
    private int currentIndex = 0; // 当前索引，用于轮询

    public PollingMapExample() {
        // 初始化Map
        map.put("Key1", "Value1");
        map.put("Key2", "Value2");
        map.put("Key3", "Value3");
    }

    /**
     * 获取下一个元素，如果到达末尾则从头开始
     * @return 下一个键值对
     */
    public Map.Entry<String, String> getNext() {
        // 检查是否到达末尾
        if (currentIndex >= map.size()) {
            currentIndex = 0; // 重置索引
        }

        // 获取当前索引的元素
        Map.Entry<String, String> entry = null;
        int i = 0;
        for (Map.Entry<String, String> e : map.entrySet()) {
            if (i == currentIndex) {
                entry = e;
                break;
            }
            i++;
        }

        // 移动到下一个索引
        currentIndex++;

        return entry;
    }

    public static void main(String[] args) throws InterruptedException {
        PollingMapExample example = new PollingMapExample();

        // 演示轮询
        while (true) {
            Map.Entry<String, String> entry = example.getNext();
            System.out.println(entry.getKey() + ": " + entry.getValue());
            Thread.sleep(1000);
        }
    }
}
